package com.github.tommas.admintpl.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.tommas.admintpl.bean.model.User;
import com.github.tommas.admintpl.security.AccountRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

public class JWTUtils {
    public static final String USERNAME_CLAIM = "username";
    public static final String USER_ID_CLAIM = "user_id";

    public static String createToken(User user, int expireAfterDays, Algorithm algorithm) {
        JWTCreator.Builder builder = JWT.create();
        builder.withSubject(user.getUsername());
        builder.withClaim(USERNAME_CLAIM, user.getUsername());
        builder.withClaim(USER_ID_CLAIM, user.getId());

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, expireAfterDays);
        builder.withExpiresAt(cal.getTime());

        return builder.sign(algorithm);
    }

    public static DecodedJWT decodeToken(String token, Algorithm algorithm) {
        JWTVerifier verifier = JWT.require(algorithm).build();
        return verifier.verify(token);
    }
}
